package com.sunseen.intelligencebus.common

import android.annotation.SuppressLint
import android.content.SharedPreferences
import com.sunseen.intelligencebus.BusApp
import kotlin.reflect.KProperty

class Preference<T>(val key: String, private val default: T) {

    companion object {
        const val PREFS_NAME = "PrefsFile"
        const val LOGIN_STATE = "LoginState"
    }

    private val prefs: SharedPreferences by lazy {
        BusApp.instance.applicationContext.getSharedPreferences(PREFS_NAME, 0)
    }

    operator fun getValue(thisRef: Any?, property: KProperty<*>): T {
        return getSharePreference(key, default)
    }

    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
        putSharePreferences(key, value)
    }

    @SuppressLint("CommitPrefEdits")
    private fun putSharePreferences(key: String, value: T) = with(prefs.edit()) {
        when (value) {
            is Int -> putInt(key, value)
            is String -> putString(key, value)
            is Boolean -> putBoolean(key, value)
            is Float -> putFloat(key, value)
            is Long -> putLong(key, value)
            else -> throw IllegalArgumentException("This type of data cannot be saved!")
        }.apply()
    }

    @Suppress("UNCHECKED_CAST")
    private fun getSharePreference(key: String, default: T): T = with(prefs) {
        val res: Any = when (default) {
            is Int -> getInt(key, default)
            is String -> getString(key, default)
            is Long -> getLong(key, default)
            is Boolean -> getBoolean(key, default)
            is Float -> getFloat(key, default)
            else -> throw IllegalArgumentException("This type of data cannot be got!")
        }
        return res as T
    }

}